import React from 'react';
import { isString } from '../../utils/is-object';
import './Validator.less';

export default () => Comp => {
  return class Wrapper extends React.Component {
    state = {
      error: undefined
    };

    validate = value => {
      const { getData } = this.props;
      const required = getData('required');
      const maxLength = getData('maxLength');
      const minLength = getData('minLength');
      let error = this.validateRequired(value, required);
      if (!error) {
        error = this.validateLength(value, maxLength, minLength);
      }
      this.setState({
        error
      });
    };

    validateRequired = (value, required) => {
      if (required && (value === null || value === undefined || value === '')) {
        return '必填';
      }
    };

    validateLength = (value, maxLength, minLength) => {
      if (!isString(value)) {
        return;
      }
      if (value.length > maxLength) {
        return `长度不能超过${maxLength}`;
      }
      if (value.length < minLength) {
        return `长度不能小于${minLength}`;
      }
    };

    render() {
      const { getData } = this.props;
      const { error } = this.state;
      const name = getData('name');
      const validateStatus = error ? 'error' : 'success';
      return (
        <div
          style={{ width: '100%', height: '100%' }}
          className={validateStatus === 'error' ? 'has-error' : ''}
        >
          <Comp
            {...this.props}
            validator={this.validate}
            validateStatus={validateStatus}
          />
          {error && (
            <div style={{ color: '#f5222d', fontSize: 14 }}>
              {name}
              {error}
            </div>
          )}
        </div>
      );
    }
  };
};
